

import { SharedObject, SharedObjectVersion } from '../types';


import { API_BASE_URL, getToken, request } from '../../utils';


export const sharingGetSharedObjects = async (conditions: {}, page: number, pageSize: number): Promise<{ total: number, data: Array<SharedObject> }> => {
    let token = getToken();
    let response = await request({
        url: `${API_BASE_URL}/shared/object/search`,
        method: 'POST',
        headers: {
            'Authorization': token
        },
        dataType: 'application/json',
        data: {
            page: page,
            page_size: pageSize,
            conditions: conditions
        }
    });
    const { data, total } = await response.json();

    return {
        total: total,
        data: data.map((item, index) => {
            return db2sharedObject(item);
        })
    };
}

export const sharingGetMySharedObjects = async (conditions: {}, page: number, pageSize: number): Promise<{ total: number, data: Array<SharedObject> }> => {
    let token = getToken();
    let response = await request({
        url: `${API_BASE_URL}/shared/object/mysearch`,
        method: 'POST',
        headers: {
            'Authorization': token
        },
        dataType: 'application/json',
        data: {
            page: page,
            page_size: pageSize,
            conditions: conditions
        }
    });
    const { data, total } = await response.json();

    return {
        total: total,
        data: data.map((item, index) => {
            return db2sharedObject(item);
        })
    };
}

export const sharingCreateSharedObject = async (obj: { name: string, icon: string, objectType: string, tags: string[], description: string }): Promise<{ id: number, identifier: string } | null> => {
    let token = getToken();
    let response = await request({
        url: `${API_BASE_URL}/shared/object/create`,
        method: 'POST',
        headers: {
            'Authorization': token
        },
        dataType: 'application/json',
        data: {
            name: obj.name,
            icon: obj.icon,
            object_type: obj.objectType,
            tags: obj.tags.join(',') + ',',
            description: obj.description,
        }
    });
    let res = await response.json();
    if (res && res.length >= 2) {
        return {
            id: res[0],
            identifier: res[1],
        };
    }
    return null;
}


export const sharingUpdateSharedObject = async (obj: { identifier: string, name: string, icon: string, tags: string[], description: string }): Promise<number> => {
    let token = getToken();
    let response = await request({
        url: `${API_BASE_URL}/shared/object/update/${encodeURIComponent(obj.identifier)}`,
        method: 'POST',
        headers: {
            'Authorization': token
        },
        dataType: 'application/json',
        data: {
            name: obj.name,
            icon: obj.icon,
            tags: obj.tags.join(',') + ',',
            description: obj.description,
        }
    });
    let res = await response.json();
    if (res) {
        return res;
    }
    return 0;
}



export const sharingRemoveSharedObjectById = async (identifier: string): Promise<void> => {
    //查看token是否设置
    let token = getToken();
    let response = await request({
        url: `${API_BASE_URL}/shared/object/remove/${encodeURIComponent(identifier)}`,
        method: 'GET',
        headers: {
            'Authorization': token
        },
        dataType: 'application/json',
    });
    return;
}

export const sharingQuerySharedObjectById = async (identifier: string): Promise<SharedObject | null> => {
    //查看token是否设置
    let token = getToken();
    let response = await request({
        url: `${API_BASE_URL}/shared/object/get_by_identifier/${encodeURIComponent(identifier)}`,
        method: 'GET',
        headers: {
            'Authorization': token
        },
        dataType: 'application/json',
    });
    try {
        const item = await response.json();
        let app: SharedObject = db2sharedObject(item);
        return app;
    } catch (error) {
        console.log(error);
    }
    return null;
}

export const sharingUploadSharedObjectVersion = async (obj: { identifier: string, version: string, download: string, description: string }): Promise<number | null> => {
    let token = getToken();
    let response = await request({
        url: `${API_BASE_URL}/shared/objver/create`,
        method: 'POST',
        headers: {
            'Authorization': token
        },
        dataType: 'application/json',
        data: {
            identifier: obj.identifier,
            version: obj.version,
            download: obj.download,
            description: obj.description,
        }
    });
    let res = await response.text();
    console.log(res);
    if (res) {
        return res;
    }
    return null;

}



const db2sharedObject = (item: any): SharedObject => {
    let tagsStr = item.tags;
    let tags = [];
    if (tagsStr) {
        tags = tagsStr.split(',').filter(item => item !== '');
    }
    return {
        id: item.id,
        userId: item.user_id,
        identifier: item.identifier,
        name: item.name,
        icon: item.icon,
        objectType: item.object_type,
        tags: tags,
        description: item.description,
        createdAt: item.created_at,
    };
}


export const sharingGetSharedObjectVersions = async (identifier: string, page: number, pageSize: number): Promise<{ total: number, data: Array<SharedObjectVersion> }> => {
    let token = getToken();
    let response = await request({
        url: `${API_BASE_URL}/shared/objver/search/${encodeURIComponent(identifier)}`,
        method: 'POST',
        headers: {
            'Authorization': token
        },
        dataType: 'application/json',
        data: {
            page: page,
            page_size: pageSize,
            conditions: {}
        }
    });
    const { data, total } = await response.json();

    return {
        total: total,
        data: data.map((item, index) => {
            return db2sharedObjectVersion(item);
        })
    };
}



const db2sharedObjectVersion = (item: any): SharedObjectVersion => {

    return {
        id: item.id,
        identifier: item.identifier,
        version: item.version,
        download: item.download,
        description: item.description,
        createdAt: item.created_at,
    };
}


export default {};